package no.saiboten.tourbuilder.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.saiboten.tourbuilder.login.AuthorizationLevel;
import no.saiboten.tourbuilder.user.UserStatus;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AdminInterceptor extends HandlerInterceptorAdapter implements
		HandlerInterceptor {

	@Autowired
	UserStatus userStatus;

	final Logger LOGGER = Logger.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {

		LOGGER.debug("In prehandle!");
		if (userStatus.isAuthenticated()) {
			if (userStatus.getUser().getAuthLevel()
					.equals(AuthorizationLevel.ADMIN)) {
				LOGGER.debug("User has access to resource");
				return true;
			}
		}

		LOGGER.debug("User has no access to resource - redirect to error page");
		arg1.sendRedirect("/tourbuilder/error");
		return false;
	}

}
